package com.buss.articlegroup.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.p3.core.common.utils.DateUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.buss.areainfo.entity.AreaInfoEntity;
import com.buss.articlegroup.entity.ArticleGroupInfoEntity;
import com.buss.articlegroup.entity.BnsGroupArea;
import com.buss.articlegroup.service.ArticleGroupInfoServiceI;
import com.buss.user.entity.BnsUsersInfoEntity;



/**   
 * @Title: Controller
 * @Description: 版块信息表
 * @author onlineGenerator
 * @date 2016-08-08 17:19:33
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/articleGroupInfoController")
public class ArticleGroupInfoController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ArticleGroupInfoController.class);

	@Autowired
	private ArticleGroupInfoServiceI articleGroupInfoService;
	@Autowired
	private SystemService systemService;
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 版块信息表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/buss/articlegroup/articleGroupInfoList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ArticleGroupInfoEntity articleGroupInfo,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ArticleGroupInfoEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, articleGroupInfo, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		cq.addOrder("createTime", SortDirection.desc);
		this.articleGroupInfoService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除版块信息表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(ArticleGroupInfoEntity articleGroupInfo, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		articleGroupInfo = systemService.getEntity(ArticleGroupInfoEntity.class, articleGroupInfo.getId());
		message = "版块信息表删除成功";
		try{
			articleGroupInfoService.delete(articleGroupInfo);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "版块信息表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除版块信息表
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "版块信息表删除成功";
		try{
			for(String id:ids.split(",")){
				ArticleGroupInfoEntity articleGroupInfo = systemService.getEntity(ArticleGroupInfoEntity.class, 
				id
				);
				articleGroupInfoService.delete(articleGroupInfo);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "版块信息表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加版块信息表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ArticleGroupInfoEntity articleGroupInfo, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "版块信息表添加成功";
		try{
			String userIds = request.getParameter("userId");
			String userNames = request.getParameter("userName");
			articleGroupInfo.setGroupManageId(userIds);
			articleGroupInfo.setArticleGroupManage(userNames);	//保存 版主
			articleGroupInfo.setCreateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
			String quyuId = articleGroupInfo.getAreaId();
			AreaInfoEntity areaEntity = systemService.getEntity(AreaInfoEntity.class, quyuId);
			articleGroupInfo.setAreaName(areaEntity.getAreaName()); 
			articleGroupInfoService.save(articleGroupInfo);
			BnsGroupArea bnsGroupArea = new BnsGroupArea();
			bnsGroupArea.setAreaId(quyuId);
			bnsGroupArea.setGroupId(articleGroupInfo.getId());
			systemService.save(bnsGroupArea);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "版块信息表添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新版块信息表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(ArticleGroupInfoEntity articleGroupInfo, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "版块信息表更新成功";
		ArticleGroupInfoEntity t = articleGroupInfoService.get(ArticleGroupInfoEntity.class, articleGroupInfo.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(articleGroupInfo, t);
			String userIds = request.getParameter("userId");
			String userNames = request.getParameter("userName");
			t.setGroupManageId(userIds);
			t.setArticleGroupManage(userNames);	//保存 版主
			
			String quyuId = t.getAreaId();
			AreaInfoEntity areaEntity = systemService.getEntity(AreaInfoEntity.class, quyuId);
			t.setAreaName(areaEntity.getAreaName()); 
			
			articleGroupInfoService.saveOrUpdate(t);
			
			BnsGroupArea bnsGroupArea = new BnsGroupArea();
			bnsGroupArea.setAreaId(quyuId);
			bnsGroupArea.setGroupId(articleGroupInfo.getId());
			systemService.save(bnsGroupArea);
			
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "版块信息表更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 版块信息表新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(ArticleGroupInfoEntity articleGroupInfo, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(articleGroupInfo.getId())) {
			articleGroupInfo = articleGroupInfoService.getEntity(ArticleGroupInfoEntity.class, articleGroupInfo.getId());
			req.setAttribute("articleGroupInfoPage", articleGroupInfo);
			idandname(req, articleGroupInfo);
		}
		
		return new ModelAndView("com/buss/articlegroup/articleGroupInfo-add");
	}
	/**
	 * 版块信息表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(ArticleGroupInfoEntity articleGroupInfo, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(articleGroupInfo.getId())) {
			articleGroupInfo = articleGroupInfoService.getEntity(ArticleGroupInfoEntity.class, articleGroupInfo.getId());
			req.setAttribute("articleGroupInfoPage", articleGroupInfo);
			idandname(req, articleGroupInfo);
		}
		return new ModelAndView("com/buss/articlegroup/articleGroupInfo-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","articleGroupInfoController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(ArticleGroupInfoEntity articleGroupInfo,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(ArticleGroupInfoEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, articleGroupInfo, request.getParameterMap());
		List<ArticleGroupInfoEntity> articleGroupInfos = this.articleGroupInfoService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"版块信息表");
		modelMap.put(NormalExcelConstants.CLASS,ArticleGroupInfoEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("版块信息表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,articleGroupInfos);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(ArticleGroupInfoEntity articleGroupInfo,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"版块信息表");
    	modelMap.put(NormalExcelConstants.CLASS,ArticleGroupInfoEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("版块信息表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ArticleGroupInfoEntity> listArticleGroupInfoEntitys = ExcelImportUtil.importExcel(file.getInputStream(),ArticleGroupInfoEntity.class,params);
				for (ArticleGroupInfoEntity articleGroupInfo : listArticleGroupInfoEntitys) {
					articleGroupInfoService.save(articleGroupInfo);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}

	/**
	 * 选择会员跳转页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "chooseMb")
	public ModelAndView chooseMb(HttpServletRequest request) {
		//--author：zhoujf-----start----date:20150531--------for: 编辑用户，选择角色,弹出的角色列表页面，默认没选中
		ModelAndView mv = new ModelAndView("com/buss/articlegroup/chooseMb"); 
		String ids = oConvertUtils.getString(request.getParameter("ids"));
		mv.addObject("ids", ids);
		return mv;
		//--author：zhoujf-----end------date:20150531--------for: 编辑用户，选择角色,弹出的角色列表页面，默认没选中
	}
	
	/**
	 * 会员显示列表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridChooseMb")
	public void datagridChooseMb(BnsUsersInfoEntity bnsUsersEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(BnsUsersInfoEntity.class, dataGrid);
		//cq.addOrder(ordername, ordervalue);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, bnsUsersEntity);
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 选择区域跳转页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "quYu")
	public ModelAndView quYu(HttpServletRequest request) {
		//--author：zhoujf-----start----date:20150531--------for: 编辑用户，选择角色,弹出的角色列表页面，默认没选中
		ModelAndView mv = new ModelAndView("com/buss/areainfo/quYus"); 
		String ids = oConvertUtils.getString(request.getParameter("ids"));
		mv.addObject("ids", ids);
		return mv;
		//--author：zhoujf-----end------date:20150531--------for: 编辑用户，选择角色,弹出的角色列表页面，默认没选中
	}

	/**
	 * 区域显示列表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridQuYu")
	public void datagridQuYu(AreaInfoEntity areInfo, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(AreaInfoEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, areInfo);
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	public void idandname(HttpServletRequest req, ArticleGroupInfoEntity articleGroupInfoEntity) {
		req.setAttribute("areaId", articleGroupInfoEntity.getAreaId());
		req.setAttribute("areaName", articleGroupInfoEntity.getAreaName());
		req.setAttribute("userName", articleGroupInfoEntity.getArticleGroupManage());
	}

	/**
	 * 版块详情信息
	 * @param request
	 * @return
	 */
	public ModelAndView groupInfo(HttpServletRequest request){
		return new ModelAndView("front/groupInfo");
	}
	
	
}
